package org.liaohailong.library.util;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;

/**
 * create by liaohailong
 * 2024/11/30 22:00
 * desc:
 */
public class IpUtil {

    public static String getLocalIpAddress(@NonNull Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        // Convert the int IP address to a string (xxx.xxx.xxx.xxx format)
        return String.format(Locale.getDefault(), "%d.%d.%d.%d",
                (ipAddress & 0xff),
                (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff),
                (ipAddress >> 24 & 0xff));
    }
}
